package javango.contrib.sessions;

import java.util.HashSet;
import java.util.Set;

public abstract class Session {
	// TODO Move this to an interface,  refactor the messages and error stuff to BaseSession or SessionBaes or AbstractSession

	public abstract void clear(String key);
	public abstract void put(String key, Object value);
	public abstract Object get(String key);

	protected Set<String> getSet(String key) {
		Set<String> messages = (Set)get(key);
		if (messages == null) {
			messages = new HashSet<String>();
			put(key, messages);
		}
		return messages;
	}

	public void addMessage(String message, Object... args ) {
		getSet("javango.messages").add(String.format(message, args));
	}
	
	public void addMessage(String message) {
		getSet("javango.messages").add(message);
	}

	public void addError(String error, Object... args) {
		getSet("javango.errors").add(String.format(error, args));
	}
	
	public void addError(String error) {
		getSet("javango.errors").add(error);
	}
	
	/**
	 * Returns the Set of messages,  the message set will be removed from the user's session.
	 * @return
	 */
	public Set<String> getAndClearMessages() {
		Set<String> messages = getSet("javango.messages");
		clear("javango.messages");
		return messages;
	}
	
	/**
	 * Returns the Set of errors,  the error set will be removed from the user's session.
	 * @return
	 */
	public Set<String> getAndClearErrors() {
		Set<String> messages = getSet("javango.errors");
		clear("javango.errors");
		return messages;
	}
	
	
	/**
	 * Returns the Set of messages. Changes made to the returned set will be stored in the user's session.
	 * @return
	 */
	public Set<String> getMessageSet() {
		Set<String> messages = getSet("javango.messages");
		return messages;
	}
	
	/**
	 * Returns the Set of errors. Changes made to the returned set will be stored in the user's session
	 * @return
	 */
	public Set<String> getErrorSet() {
		Set<String> messages = getSet("javango.errors");
		return messages;
	}	

}
